package cn.gov.pbc.tims.service;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.ResourceBundle;

import javax.mail.BodyPart;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import javax.mail.search.AndTerm;
import javax.mail.search.ComparisonTerm;
import javax.mail.search.ReceivedDateTerm;
import javax.mail.search.SearchTerm;
import javax.mail.search.SentDateTerm;
import javax.mail.search.SubjectTerm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Service;

import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.IMAPMessage;
import com.sun.mail.imap.IMAPStore;
import com.sun.mail.pop3.POP3Folder;

import cn.gov.pbc.tims.entity.Fileup;
import cn.gov.pbc.tims.entity.Mail;
import cn.gov.pbc.tims.serviceInt.IMailService;
import cn.gov.pbc.tims.util.FileOperateUtil;
import cn.gov.pbc.tims.util.PageData;
@Service("imapMailService")
public class ImapMailService implements IMailService {

	@Override
	public IMAPFolder getFolder(String userName,String password) throws MessagingException {
		ResourceBundle resource=ResourceBundle.getBundle("mailconfig");
        Properties prop = System.getProperties();  
        prop.put("mail.store.protocol", "imap"); 
        prop.put("mail.imap.host", resource.getString("mail.imap.host"));
        Session session = Session.getInstance(prop);      
        IMAPStore  store =(IMAPStore)session.getStore("imap"); // 使用imap会话机制，连接服务器      
        store.connect(userName, password); 
        IMAPFolder folder =(IMAPFolder)store.getFolder("INBOX");
		folder.open(Folder.READ_ONLY);
		return folder;
	}

	@Override
	public PageData getMail(Folder folder,Integer page, Integer rows,HttpServletRequest request) throws Exception {
		 int total = 0;      
			Integer startRow=(page-1)*rows;
			System.out.println(Calendar.getInstance().getTime().getSeconds());
			Message[] messages;
			/*if(total>=startRow+rows)
				 messages = folder.getMessages(startRow, startRow+rows-1);
			else
				  messages = folder.getMessages(startRow, total);*/
			//System.out.println("邮件数量:　" + total);
			//按照日期排序
			//SortTerm[] term =new SortTerm[1];
			//term[0]=SortTerm.ARRIVAL;
		    //messages=folder.getSortedMessages(term);
			 SearchTerm comparisonTermGe;
			 String date1=request.getParameter("sentDate_end");
			if(null!=date1)
			{
				Calendar cal=Calendar.getInstance();
				SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
				Date date=format.parse(date1);
				cal.setTime(date);
				comparisonTermGe=new ReceivedDateTerm(ComparisonTerm.GT,date);
				}
			else
			{
				Calendar calendar = Calendar.getInstance();
				calendar.set(Calendar.DAY_OF_MONTH, 1); 
				calendar.add(Calendar.DATE, -1); 
		        comparisonTermGe = new SentDateTerm(ComparisonTerm.GE, calendar.getTime());   
			}
			String title=request.getParameter("title");
			if(null!=title)
			{
				SubjectTerm subjectTerm =new SubjectTerm(title) ;
				SearchTerm comparisonAndTerm = new AndTerm(comparisonTermGe, subjectTerm); 
				messages=folder.search(comparisonAndTerm);
			}
			else
			   messages=folder.search(comparisonTermGe);
			   total=messages.length;
		    int nub=0;
		    if(total>=startRow+rows)
		    	nub=rows;
			else
				nub=total-startRow;
			Mail re = null;
			List results=new ArrayList<Mail>();

			for (int i = (total-startRow-1); i > total-startRow-1-nub; i--) {
				MimeMessage message=(MimeMessage) messages[i];
				re = new Mail(message,String.valueOf(((IMAPFolder)folder).getUID(message)));
				results.add(re);
			}
			System.out.println(Calendar.getInstance().getTime().getSeconds());
			folder.close();
			folder.getStore().close();
			PageData grid_data=new PageData();
			grid_data.setValue(total, results);
     return grid_data;
	}
	public MimeMessage getMessageByUid(Folder  folder,String uid) throws MessagingException
	{
		MimeMessage message1=(MimeMessage)((IMAPFolder) folder).getMessageByUID(Long.valueOf(uid));
		return message1;
	}
	
	@Override
	public void getAttachment(Folder folder,String uid,String fileName,HttpServletRequest request, HttpServletResponse response) throws IOException, Exception {
		MimeMessage message1=getMessageByUid((IMAPFolder)folder,uid);
		Mail mail=new Mail(message1);
		Part part=mail.getAttachmentPart(fileName,message1);
		InputStream iss=part.getInputStream();
	    String contentType = "application/force-download";  
	    long fileLength =part.getSize();
	    
	    request.setCharacterEncoding("UTF-8"); 
	    response.setContentType(contentType);  
        response.setHeader("Content-disposition", "attachment; filename="  
                + new String(fileName.getBytes("utf-8"), "ISO8859-1"));  
        response.setHeader("Content-Length", String.valueOf(fileLength));  
	    FileOperateUtil.download(response.getOutputStream(),iss,fileLength); 
	    folder.close();
		folder.getStore().close(); 
	}

	@Override
	public String getDocContent(Folder folder,String uid,String fileName,HttpServletRequest request, HttpServletResponse response) throws Exception {
		String content="";
		MimeMessage message1=getMessageByUid((IMAPFolder)folder,uid);
		Mail mail=new Mail(message1);
			InputStream iss=mail.getAttachment(fileName,message1);
			System.out.println(iss.available());
			
			if(fileName.endsWith(".doc")||fileName.endsWith(".docx"))
			{
				content=FileOperateUtil.readWord(iss, ".doc");
			}
			else if(fileName.endsWith(".docx"))
			{
				content=FileOperateUtil.readWord(iss, ".docx") ;
			}
			else if(fileName.endsWith(".wps"))
			{
				content=FileOperateUtil.readWord(iss, ".doc");
			}
			else if(fileName.endsWith(".pdf"))
			 {
				content=FileOperateUtil.readPdf(iss);
			  }
			else
			 {
				content=FileOperateUtil.readTxt(iss);
			  }
			
			folder.close();
			folder.getStore().close();
			return content;
	}
	 
}
